public class Solution738 {
    public int monotoneIncreasingDigits(int n) {
        String s=String.valueOf(n);
        int flag=-1;
        for (int i=0;i<s.length()-1;i++){
            if (s.charAt(i)>s.charAt(i+1)){
                flag=i;
                break;
            }
        }
        if (flag==-1){
            return n;
        }
        while (flag>0 && s.charAt(flag)==s.charAt(flag-1)){
            flag--;
        }
        StringBuilder stringBuilder=new StringBuilder();
        for (int i=0;i<flag;i++){
            stringBuilder.append(s.charAt(i));
        }
        stringBuilder.append((char)(s.charAt(flag)-1));
        for (int i=flag+1;i<s.length();i++){
            stringBuilder.append(9);
        }
        if (stringBuilder.charAt(0)=='0'){
            stringBuilder.deleteCharAt(0);
        }
        return Integer.parseInt(stringBuilder.toString());
    }

    public static void main(String[] args) {
        System.out.println(new Solution738().monotoneIncreasingDigits(322));
    }
}
